import { getCookie } from '@/utils/cookie';
import { RequestConfig } from '@umijs/max';
import { message } from 'antd';
import Header from './components/Header';

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{ name: string }> {
  return { name: '@umijs/max' };
}

export const layout = () => {
  return {
    logo: require('@/assets/img/heima.png'),
    title: '电商后台管理系统',
    menu: {
      locale: false,
    },
    siderWidth: 200,
    layout: 'mix',
    rightRender: () => <Header />,
  };
};

export const request: RequestConfig = {
  baseURL: 'http://127.0.0.1:8888/api/private/v1/',
  timeout: 5000,

  // 请求拦截
  requestInterceptors: [
    (config: any) => {
      const token = getCookie('token');
      if (token) {
        // 如果有token,在头部加上这个消息
        config.headers.Authorization = token;
      }
      return config;
    },
  ],
  // 响应拦截
  responseInterceptors: [
    (res) => {
      return res;
    },
    [
      (response: any) => {
        if (
          response.data.meta.msg === '密码错误' ||
          response.data.meta.msg === '用户名不存在'
        ) {
          message.open({
            type: 'error',
            content: response.data.meta.msg,
            duration: 1.5,
          });
        } else if (response.data.meta.msg === '无效token') {
          message.open({
            type: 'error',
            content: '请先登录',
            duration: 0.5,
            onClose: () => {
              window.location.href = '/login';
            },
          });
        }
        return response;
      },
    ],
  ],

  // 错误
  errorConfig: {
    errorHandler(err: any) {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        message.open({
          type: 'error',
          content: '网络出错, 请重试',
          duration: 1.5,
        });
      }
      return Promise.reject(err);
    },
  },
};
